﻿using Fiddler;
using FiddlerExUtils.Helper;
using FiddlerExUtils.Tools;
using FiddlerInspectorsEx.Properties;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FiddlerInspectorsEx
{
    public partial class MockFrm : Form
    {
       
        /// <summary>
        /// URL Replace当前编辑行的数据库id索引
        /// </summary>
        private string databaseIndex = "-1";
        private int dataGridViewRowIndex = 0;

        public MockFrm()
        {
            InitializeComponent();
            RTB_OldReq.SetToolsVisible(false, true, false);
            RTB_NewReq.SetToolsVisible(false, true, false);
            RTB_OldRes.SetToolsVisible(false, true, false);
            RTB_NewRes.SetToolsVisible(false, true, false);
            //RTB_NewReq.Width = 295;
            //RTB_NewRes.Width = 295;
        }

        private void RTB_NewReq_DragDrop(object sender, DragEventArgs e)
        {
            RTB_NewReq.BackColor = SystemColors.Control;
            splitContainer5.Panel2.BackColor = SystemColors.Control;
            Session[] data = (Session[])e.Data.GetData("Fiddler.Session[]");
            if (data == null || data.Length != 1) return;

            ComboBox_Host.Text = data[0].fullUrl.Contains("?") ? data[0].fullUrl.Split('?')[0] : data[0].fullUrl;
            string reqBody = data[0].GetRequestBodyAsString();
            RTB_OldReq.Clear();
            RTB_NewReq.SetText(CommonFunction.ConvertJsonString(reqBody, false));
            CB_RspCode.Text = data[0].responseCode.ToString();
            databaseIndex = "-1";
            dataGridViewRowIndex = 0;
            Btn_SaveReplace.Text = "添加(&A)";

        }

        private void RTB_NewReq_DragOver(object sender, DragEventArgs e)
        {
            //必须在DragOver下设置Effect类型，否则UserControl中的RichTextBox无法接收拖放的数据
            Session[] data = (Session[])e.Data.GetData("Fiddler.Session[]");
            if (data == null || data.Length != 1) return;
            e.Effect = e.Data.GetDataPresent("Fiddler.Session[]") ? DragDropEffects.Copy : DragDropEffects.None;
        }

        private void RTB_NewReq_DragEnter(object sender, DragEventArgs e)
        {
            Session[] data = (Session[])e.Data.GetData("Fiddler.Session[]");
            if (data == null || data.Length != 1) return;
            e.Effect = e.Data.GetDataPresent("Fiddler.Session[]") ? DragDropEffects.Copy : DragDropEffects.None;
            if (e.Effect == DragDropEffects.Copy)
            {
                RTB_NewReq.BackColor = Color.LightGreen;
                splitContainer5.Panel2.BackColor = Color.LightGreen;
            }
        }

        private void RTB_NewReq_DragLeave(object sender, EventArgs e)
        {
            RTB_NewReq.BackColor = SystemColors.Control;
            splitContainer5.Panel2.BackColor = SystemColors.Control;
        }

        private void RTB_NewRes_DragDrop(object sender, DragEventArgs e)
        {
            RTB_NewRes.BackColor = SystemColors.Control;
            splitContainer6.Panel2.BackColor = SystemColors.Control;
            Session[] data = (Session[])e.Data.GetData("Fiddler.Session[]");
            if (data == null || data.Length != 1) return;

            ComboBox_Host.Text = data[0].fullUrl.Contains("?") ? data[0].fullUrl.Split('?')[0] : data[0].fullUrl;
            string resBody = data[0].GetResponseBodyAsString();
            RTB_OldRes.Clear();
            RTB_NewRes.SetText(CommonFunction.ConvertJsonString(resBody, false));
            CB_RspCode.Text = data[0].responseCode.ToString();
            databaseIndex = "-1";
            dataGridViewRowIndex = 0;
            Btn_SaveReplace.Text = "添加(&A)";

        }

        private void RTB_NewRes_DragOver(object sender, DragEventArgs e)
        {
            //必须在DragOver下设置Effect类型，否则UserControl中的RichTextBox无法接收拖放的数据
            Session[] data = (Session[])e.Data.GetData("Fiddler.Session[]");
            if (data == null || data.Length != 1) return;
            e.Effect = e.Data.GetDataPresent("Fiddler.Session[]") ? DragDropEffects.Copy : DragDropEffects.None;
        }

        private void RTB_NewRes_DragEnter(object sender, DragEventArgs e)
        {
            Session[] data = (Session[])e.Data.GetData("Fiddler.Session[]");
            if (data == null || data.Length != 1) return;
            e.Effect = e.Data.GetDataPresent("Fiddler.Session[]") ? DragDropEffects.Copy : DragDropEffects.None;
            if (e.Effect == DragDropEffects.Copy)
            {
                RTB_NewRes.BackColor = Color.LightGreen;
                splitContainer6.Panel2.BackColor = Color.LightGreen;
            }
        }

        private void RTB_NewRes_DragLeave(object sender, EventArgs e)
        {
            RTB_NewRes.BackColor = SystemColors.Control;
            splitContainer6.Panel2.BackColor = SystemColors.Control;
        }

        private void Btn_SaveReplace_Click(object sender, EventArgs e)
        {
            string url = ComboBox_Host.Text.Trim();
            string responseCode = CB_RspCode.Text.Trim();
            string oldReq = RTB_OldReq.GetText().Trim();
            string newReq = RTB_NewReq.GetText().Trim();
            string oldRes = RTB_OldRes.GetText().Trim();
            string newRes = RTB_NewRes.GetText().Trim();
            AddToMockList(url, responseCode, oldReq, newReq, oldRes, newRes, databaseIndex);
        }

        public void AddToMockList(string url, string responseCode, string oldReq, string newReq, string oldRes, string newRes, string databaseIndex)
        {
            string mockMark = textBox_mark.Text;
            if (databaseIndex != "-1")
            {
                JSONView.sqllite.UpdateValues("mock", SqliteHelper.columnName, new string[] { databaseIndex, "1", url, oldReq, newReq, oldRes, newRes, responseCode, mockMark }, "ID", databaseIndex, "=");
            }
            else
            {
                JSONView.sqllite.InsertValues("mock", new string[] { "1", url, oldReq, newReq, oldRes, newRes, responseCode, mockMark });
            }

            RefreshMockList();
            //ComboBox_Host.Text = "";
            //DataGridView_BodyReplace.ClearSelection();
            //Btn_ClearReplace_Click(null, null);
        }

        private void Btn_ClearReplace_Click(object sender, EventArgs e)
        {
            ComboBox_Host.Text = "";
            CB_RspCode.SelectedIndex = 0;
            textBox_mark.Clear();
            RTB_OldReq.Clear();
            RTB_NewReq.Clear();
            RTB_OldRes.Clear();
            RTB_NewRes.Clear();
            RTB_OldRes.Focus();

            databaseIndex = "-1";
            dataGridViewRowIndex = 0;
            Btn_SaveReplace.Text = "添加(&A)";
            splitContainer6.SplitterDistance = splitContainer6.Width / 2 -28;
            splitContainer5.SplitterDistance = splitContainer5.Width / 2 - 28;
        }

        private void TB_OldReq_TextChanged(object sender, EventArgs e)
        {
            ContentCheck();
        }

        private void TB_NewReq_TextChanged(object sender, EventArgs e)
        {
            ContentCheck();
        }

        private void TB_OldRes_TextChanged(object sender, EventArgs e)
        {
            ContentCheck();
        }

        private void TB_NewRes_TextChanged(object sender, EventArgs e)
        {
            ContentCheck();
        }

        private void ComboBox_Host_TextChanged(object sender, EventArgs e)
        {
            ContentCheck();
        }

        private void ContentCheck()
        {
            string host = ComboBox_Host.Text.Trim();
            string oldReq = RTB_OldReq.GetText().Trim();
            string newReq = RTB_NewReq.GetText().Trim();
            string oldRes = RTB_OldRes.GetText().Trim();
            string newRes = RTB_NewRes.GetText().Trim();
            if (host != "")
            {
                if (newReq != "")
                {
                    if (oldRes != "" && newRes == "")
                    {
                        Btn_SaveReplace.Enabled = false;
                    }
                    else
                    {
                        Btn_SaveReplace.Enabled = true;
                    }

                }
                else if (newRes != "")
                {
                    if (oldReq != "" && newReq == "")
                    {
                        Btn_SaveReplace.Enabled = false;
                    }
                    else
                    {
                        Btn_SaveReplace.Enabled = true;
                    }
                }
                else
                {
                    Btn_SaveReplace.Enabled = false;
                }
            }
            else
            {
                Btn_SaveReplace.Enabled = false;
            }

            if (newReq == "")
            {
                tabPage_RequestReplace.ImageKey = "Replace-off.png";
            }
            else
            {
                tabPage_RequestReplace.ImageKey = "Replace-on.png";
            }
            if (newRes == "")
            {
                tabPage_ResponseReplace.ImageKey = "Replace-off.png";
            }
            else
            {
                tabPage_ResponseReplace.ImageKey = "Replace-on.png";
            }
        }

        private void DataGridView_BodyReplace_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 && e.ColumnIndex == 0)
            {
                string index = DataGridView_BodyReplace.Rows[e.RowIndex].Cells["ID"].Value.ToString();
                DataGridView_BodyReplace.ClearSelection();
                string enable = DataGridView_BodyReplace.Rows[e.RowIndex].Cells["enable"].Value.ToString();
                if (enable == "1")
                {
                    DataGridView_BodyReplace.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = Resources.switch_off;
                    DataGridView_BodyReplace.Rows[e.RowIndex].Cells["enable"].Value = "0";
                    JSONView.sqllite.UpdateValues("mock", new string[] { "Enable" }, new string[] { "0" }, "ID", index, "=");
                }
                else
                {
                    DataGridView_BodyReplace.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = Resources.switch_on;
                    DataGridView_BodyReplace.Rows[e.RowIndex].Cells["enable"].Value = "1";
                    JSONView.sqllite.UpdateValues("mock", new string[] { "Enable" }, new string[] { "1" }, "ID", index, "=");
                }
                DataGridView_BodyReplace.Rows[dataGridViewRowIndex].Selected = true;
            }
            else if (e.RowIndex > -1 && e.ColumnIndex > 0)
            {
                dataGridViewRowIndex = e.RowIndex;
                databaseIndex = DataGridView_BodyReplace.Rows[e.RowIndex].Cells["ID"].Value.ToString();
                SQLiteDataReader reader = JSONView.sqllite.ReadTable("mock", SqliteHelper.columnName, new string[] { "ID" }, new string[] { "=" }, new string[] { databaseIndex });
                DataTable table = new DataTable();
                table.Load(reader);
                //加载Mock数据
                for (int i = 0; i < table.Rows.Count; i++) //遍历行
                {
                    ComboBox_Host.Text = table.Rows[i][2].ToString();
                    RTB_OldReq.SetText(table.Rows[i][3].ToString().Replace('\"', '"'));
                    RTB_NewReq.SetText(table.Rows[i][4].ToString().Replace('\"', '"'));
                    RTB_OldRes.SetText(table.Rows[i][5].ToString().Replace('\"', '"'));
                    RTB_NewRes.SetText(table.Rows[i][6].ToString().Replace('\"', '"'));
                    CB_RspCode.Text = table.Rows[i][7].ToString();
                    textBox_mark.Text = table.Rows[i][8].ToString();

                    Btn_SaveReplace.Text = "保存(&S)";
                    //判断展示哪一个tab
                    if (RTB_OldRes.GetText() == "" && RTB_NewRes.GetText() != "")
                    {
                        TabControl_BodyReplace.SelectedIndex = 1;
                        splitContainer6.SplitterDistance = 25;
                        //RTB_NewRes.Focus();
                    }
                    else if (RTB_OldRes.GetText() != "" && RTB_NewRes.GetText() != "")
                    {
                        splitContainer6.SplitterDistance = splitContainer6.Width / 2 - 28;
                    }

                    if (RTB_OldReq.GetText() == "" && RTB_NewReq.GetText() != "")
                    {
                        TabControl_BodyReplace.SelectedIndex = 0;
                        splitContainer5.SplitterDistance = 25;
                        //RTB_NewReq.Focus();
                    }
                    else if (RTB_OldReq.GetText() != "" && RTB_NewReq.GetText() != "")
                    {
                       splitContainer5.SplitterDistance = splitContainer5.Width / 2 - 28;
                    }
                }
            }
        }

        private void TabControl_BodyReplace_DragOver(object sender, DragEventArgs e)
        {
            Point pt = TabControl_BodyReplace.PointToClient(new Point(e.X, e.Y));
            if (pt.Y > 0 && pt.Y <= TabControl_BodyReplace.ItemSize.Height)
            {
                if (pt.X > 0 && pt.X <= TabControl_BodyReplace.ItemSize.Width)
                {
                    TabControl_BodyReplace.SelectedIndex = 0;
                }
                else if (pt.X > TabControl_BodyReplace.ItemSize.Width && pt.X <= 2 * TabControl_BodyReplace.ItemSize.Width)
                {
                    TabControl_BodyReplace.SelectedIndex = 1;
                }
            }
        }

        private void MockFrm_Load(object sender, EventArgs e)
        {
            CB_RspCode.SelectedIndex = 0;
            TabControl_BodyReplace.SelectedIndex = 1;
            TabControl_BodyReplace.SelectedIndex = 0;
            //Body替换事件绑定
            RTB_OldReq.richTextBox1.TextChanged += TB_OldReq_TextChanged;
            RTB_NewReq.richTextBox1.TextChanged += TB_NewReq_TextChanged;
            RTB_OldRes.richTextBox1.TextChanged += TB_OldRes_TextChanged;
            RTB_NewRes.richTextBox1.TextChanged += TB_NewRes_TextChanged;
            //Body替换拖放数据事件绑定
            RTB_NewRes.DragEnter += RTB_NewRes_DragEnter;
            RTB_NewRes.DragDrop += RTB_NewRes_DragDrop;
            RTB_NewRes.DragOver += RTB_NewRes_DragOver;
            RTB_NewRes.DragLeave += RTB_NewRes_DragLeave;

            RTB_NewReq.DragEnter += RTB_NewReq_DragEnter;
            RTB_NewReq.DragDrop += RTB_NewReq_DragDrop;
            RTB_NewReq.DragOver += RTB_NewReq_DragOver;
            RTB_NewReq.DragLeave += RTB_NewReq_DragLeave;

            RTB_NewRes.richTextBox1.DragEnter += RTB_NewRes_DragEnter;
            RTB_NewRes.richTextBox1.DragDrop += RTB_NewRes_DragDrop;
            RTB_NewRes.richTextBox1.DragOver += RTB_NewRes_DragOver;
            RTB_NewRes.richTextBox1.DragLeave += RTB_NewRes_DragLeave;

            RTB_NewReq.richTextBox1.DragEnter += RTB_NewReq_DragEnter;
            RTB_NewReq.richTextBox1.DragDrop += RTB_NewReq_DragDrop;
            RTB_NewReq.richTextBox1.DragOver += RTB_NewReq_DragOver;
            RTB_NewReq.richTextBox1.DragLeave += RTB_NewReq_DragLeave;

            string tips = "不为空，则Body部分替换，替换多个时请换行；\n若为空，则Body全部替换";
            toolTip1.SetToolTip(RTB_OldReq.richTextBox1, tips);
            toolTip1.SetToolTip(RTB_OldRes.richTextBox1, tips);

            RefreshMockList();
        }

        private void MockFrm_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        private void DataGridView_BodyReplace_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            //Btn_ClearReplace_Click(null, null);
            //BodyReplaceModel model = DataGridView_BodyReplace.Rows[e.RowIndex].Cells["replaceData"].Value as BodyReplaceModel;
            //JSONView.MockList.RemoveAt(e.RowIndex);
        }

        private void DataGridView_BodyReplace_Leave(object sender, EventArgs e)
        {
            //DataGridView_BodyReplace.ClearSelection();
        }

        public void RefreshMockList()
        {
            DataGridView_BodyReplace.Rows.Clear();
            SQLiteDataReader reader = JSONView.sqllite.ReadFullTable("mock");
            DataTable table = new DataTable();
            table.Load(reader);
            //加载Mock数据
            for(int i = 0; i < table.Rows.Count; i++) //遍历行
            {
                DataGridView_BodyReplace.Rows.Add(table.Rows[i][1].ToString() == "1" ? Resources.switch_on : Resources.switch_off, table.Rows[i][2].ToString(), table.Rows[i][8].ToString(), table.Rows[i][1].ToString(), table.Rows[i][0].ToString());
            }
            if (dataGridViewRowIndex == 0 && table.Rows.Count > 0)
            {
                dataGridViewRowIndex = table.Rows.Count - 1;
            }
            if (dataGridViewRowIndex < table.Rows.Count && table.Rows.Count > 0)
            {
                DataGridView_BodyReplace.FirstDisplayedScrollingRowIndex = dataGridViewRowIndex;
                DataGridView_BodyReplace.Rows[dataGridViewRowIndex].Selected = true;
                DataGridView_BodyReplace_CellClick(DataGridView_BodyReplace, new DataGridViewCellEventArgs(1, dataGridViewRowIndex));
            }
           
        }

        private void DataGridView_BodyReplace_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete && DataGridView_BodyReplace.SelectedRows.Count == 1)
            {
                DialogResult result = MessageBox.Show(this, "确认要删除吗？", "删除提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    JSONView.sqllite.DeleteValuesAND("mock", new string[] { "ID" }, new string[] { DataGridView_BodyReplace.SelectedRows[0].Cells["ID"].Value.ToString() }, new string[] { "=" });
                    Btn_ClearReplace_Click(null, null);
                    FiddlerApplication.UI.SetStatusText("Mock删除成功");
                }
                else
                {
                    e.Handled = true;
                }
            }
            else
            {
                e.Handled = true;
            }
        }

        private void DGV_ContextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            DGV_ContextMenuStrip.Hide();
            DialogResult result = MessageBox.Show(this, "确认要删除吗？", "删除提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                if (DataGridView_BodyReplace.SelectedRows.Count == 1)
                {
                    JSONView.sqllite.DeleteValuesAND("mock", new string[] { "ID" }, new string[] { DataGridView_BodyReplace.SelectedRows[0].Cells["ID"].Value.ToString() }, new string[] { "=" });
                    Btn_ClearReplace_Click(null, null);
                    DataGridView_BodyReplace.Rows.RemoveAt(DataGridView_BodyReplace.SelectedRows[0].Index);
                    FiddlerApplication.UI.SetStatusText("Mock删除成功");
                }
            }
        }

        private void DataGridView_BodyReplace_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if(e.Button == MouseButtons.Right && e.RowIndex > -1)
            {
                DataGridView_BodyReplace_CellClick(DataGridView_BodyReplace, new DataGridViewCellEventArgs(1, e.RowIndex));
                DataGridView_BodyReplace.Rows[dataGridViewRowIndex].Selected = true;
                DGV_ContextMenuStrip.Show(MousePosition.X, MousePosition.Y);
            }
        }

        private void DataGridView_BodyReplace_SelectionChanged(object sender, EventArgs e)
        {
            //if (DataGridView_BodyReplace.SelectedRows.Count == 1)
            //    DataGridView_BodyReplace_CellClick(DataGridView_BodyReplace, new DataGridViewCellEventArgs(1, DataGridView_BodyReplace.SelectedRows[0].Index));
        }
    }
}
